package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.OrderSettingDao;
import com.atguigu.pojo.OrderSetting;
import com.atguigu.service.OrderSettingService;
import com.atguigu.utils.DownLoadUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author zhengkaiyuan
 * @version 1.0
 * @create 2021-06-22 19:22
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        // 1：遍历List<OrderSetting>
        for (OrderSetting orderSetting : orderSettings) {
            // 判断当前的日期之前是否已经被设置过预约日期，使用当前时间作为条件查询数量
            Date orderDate = orderSetting.getOrderDate();
            long count = orderSettingDao.findCountByOrderDate(orderDate);
            // 如果设置过预约日期，更新number数量
            if (count > 0) {
                orderSettingDao.editNumberByOrderDate(orderSetting);
            }
            // 如果没有设置过预约日期，执行保存
            orderSettingDao.add(orderSetting);

        }

    }


    /**
     * 获取日期期间
     *
     * @param date
     * @return
     */
    private static Map<String, String> getDateRegion(String date) {
// 1.组织查询Map，dateBegin表示月份开始时间，dateEnd月份结束时间
        String dateBegin = date + "-1";
        String dateEnd = date + "-31";
        Map<String, String> map = new HashMap();
        map.put("dateBegin", dateBegin);
        map.put("dateEnd", dateEnd);
        return map;

    }

    @Override
    public List<Map<String, String>> getOrderSettingByMonth(String date) {//2019-3
        Map<String, String> dateRegion = getDateRegion(date);
        // 2.查询当前月份的预约设置
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(dateRegion);
        List<Map<String, String>> data = new ArrayList<>();
        // 3.将List<OrderSetting>，组织成List<Map>
        for (OrderSetting orderSetting : list) {
            HashMap hashMap = new HashMap<>();
            int day = orderSetting.getOrderDate().getDate();
            hashMap.put("date", day + "");
            hashMap.put("number", orderSetting.getNumber() + "");
            hashMap.put("reservations", orderSetting.getReservations() + "");
            data.add(hashMap);
        }
        return data;
    }

    //根据日期修改可预约人数  该日期存在则修改，不存在则添加
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //当前日期已经进行了预约设置，需要进行修改操作
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        //如果大于0则证明存该日期存在预约  则进行修改
        if (count > 0) {
            orderSettingDao.editNumberByDate(orderSetting);
        } else {
            //不存在则进行插入
            orderSettingDao.add(orderSetting);
        }
    }


    //关于下载当前月份的方法
    @Override
    public String downloadDate(String date, String filePath) throws Exception {
        //获取当前日期对应的数据
        Map<String, String> dateRegion = getDateRegion(date);
        // 2.查询当前月份的预约设置
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(dateRegion);
        //文件名
        String excelName = "";
        //如果当前集合不存在数据 抛出异常不存在数据，无法下载
        excelName = DownLoadUtils.createExcelToName(date, list, filePath);
        return excelName;
    }


    //创建文件的方法
    private String createExcel(String fileName, List<Map<String, String>> data, String filePath) throws IOException {
        //在内存中创建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表，指定工作表名称
        XSSFSheet sheet = workbook.createSheet(fileName);
        //创建行，0表示第一行
        XSSFRow row = sheet.createRow(0);
        //创建单元格，0表示第一个单元格
        row.createCell(0).setCellValue("orderDate");
        row.createCell(1).setCellValue("number");
        row.createCell(2).setCellValue("reservations");
        //定义每一行的索引位置
        int index = 1;
        //获取所有的行标题
        String[] rowTitle = new String[]{"date", "number", "reservations"};
        //循环向excel中添加数据
        for (Map<String, String> rowData : data) {
            row = sheet.createRow(index++);
            fillerDate(row, rowData, rowTitle);
        }
        //拼接地址
        String address = filePath + File.separator + fileName + ".xlsx";
        //通过输出流将workbook对象下载到磁盘
        FileOutputStream out = new FileOutputStream(address);
        workbook.write(out);
        out.flush();//刷新
        out.close();//关闭
        workbook.close();
        return fileName + data.size() + "条";
    }

    //填充每行数据
    private void fillerDate(XSSFRow row, Map<String, String> rowData, String[] rowTitle) {
        for (int i = 0; i < rowTitle.length; i++) {
            String value = rowData.get(rowTitle[i]);
            row.createCell(i).setCellValue(value);
        }
    }
}
